/**------------------------------------------------------------
 *
 * Copyright © 2014 rubbervalley. All rights reserved.
 *
 * @Title: PlatUploadfileController.java
 * @Package: com.rubbervalley.uyo.actions
 * @Description: 上传文件
 * @author: zl
 * @date: 下午6:08:58
 * @version: V1.0
 * 
 ------------------------------------------------------------*/
package com.rubbervalley.uyo.actions.administrator;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.regexp.RegexpMatcher;
import net.sf.json.regexp.RegexpUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.rubbervalley.framework.core.common.MessageUtil;
import com.rubbervalley.framework.core.common.ObjectMessages;
import com.rubbervalley.platform.business.PlatUploadfileService;
import com.rubbervalley.platform.domain.PlatUploadfile;
import com.rubbervalley.uyo.domain.UploadBean;
import com.rubbervalley.uyo.util.UploadFile;

@Controller
@RequestMapping(value = "/uyo")
public class PlatUploadfileController {
	@Value("${store.file.path}") 
	private String storeFilePath; // 企业文件保存地址
	@Value("${store.image.path}") 
	private String storeImagePath; // 企业图片保存地址
	@Value("${store.logo.path}") 
	private String storeLogoPath; // 企业LOGO图片保存地址
	@Value("${product.file.path}") 
	private String productFilePath; // 产品文件保存地址
	@Value("${product.image.path}") 
	private String productImagePath; // 产品图片保存地址
	@Value("${upload.image.maxsize}") 
	private Long imageMaxSize;       // 上传图片最大值
	@Autowired
	private PlatUploadfileService platUploadfileService;

	@Autowired
	private MessageUtil messageUtil;
	@Autowired
	private UploadFile uploadFile;
	@Resource
    private MessageSource  messageSource;

	private static final Logger logger = LoggerFactory
			.getLogger(PlatUploadfileController.class);

	@RequestMapping(value = "/platUploadfiles", method = RequestMethod.GET)
	String platUploadfiles(Map<String, Object> model)
	{
		logger.debug("PlatUploadfileController");
		// TODO: 初始化
		return "/uyo/platUploadfile/platUploadfiles.ftl";
	}

	/***
	 * 企业相关文件上传
	 * @throws IOException 
	 */
	@RequestMapping(value = "/platUploadfile/storeFileAdd", method = RequestMethod.POST)
	@ResponseBody
	public String add(@RequestParam("upfile") CommonsMultipartFile upfile			
			,@RequestParam(value="fileTag" , required=false) Integer fileTag   //上传文件类型标识
			,HttpServletRequest request) throws IOException
	{
		Locale locale=LocaleContextHolder.getLocale();
		UploadBean bean=new UploadBean();
		if (upfile == null) {   //没有上传文件
			bean.setState("ERROR");
			bean.setMessage(messageSource.getMessage("common.uploadfile.nofile.error", null, locale));
			return bean.toString();
		}
		String ext = upfile.getOriginalFilename();
		int idx = ext.lastIndexOf(".");
		if (idx < 0) {               //文件格式不正确
			bean.setState("ERROR");         
			bean.setMessage(messageSource.getMessage("common.uploadfile.wrongType.error", null, locale));
			return bean.toString();
		}
		ext = ext.substring(ext.lastIndexOf("."));
		if (ext.trim().length() == 0) {//文件格式不正确
			bean.setState("ERROR");
			bean.setMessage(messageSource.getMessage("common.uploadfile.wrongType.error", null, locale));
			return bean.toString();
		}
		if(fileTag!=null && fileTag !=1){    //如果上传的是图片
			String exts = "";
			if (upfile.getSize() > imageMaxSize) {//图片大小不能超过2M
				bean.setState("ERROR");
				bean.setMessage(messageSource.getMessage("common.uploadfile.filesize.error", null, locale));
				return bean.toString();
			}
			exts = "jpg|jpeg|gif|bmp|png";
			if (!checkFileExt(ext, exts)) {//图片格式不正确
				bean.setState("ERROR");
				bean.setMessage(messageSource.getMessage("common.uploadfile.wrongType.error", null, locale));
				return bean.toString();
			}
			else if(fileTag==PlatUploadfile.CONTENT_IMAGE_TAG){ //属于正文内容的图片上传
				bean= uploadFile.updateFile(upfile,request,storeFilePath,UploadFile.UPLOAD_IMAGE);
			}
			else if(fileTag==PlatUploadfile.IMAGE_TAG){         //展示图片上传
				bean= uploadFile.updateFile(upfile,request,storeImagePath,UploadFile.UPLOAD_IMAGE);
			}
			else if(fileTag==PlatUploadfile.LOGO_TAG){          //LOGO图片上传
				bean= uploadFile.updateFile(upfile,request,storeLogoPath,UploadFile.UPLOAD_IMAGE);
			}
		}
		else{
			if(fileTag==null){            						//默认为一般文件上传
				bean= uploadFile.updateFile(upfile,request,storeFilePath,UploadFile.UPLOAD_FILE);
			}
		}	
		return bean.toString();
			
	}
	/***
	 * 图片上传
	 * @throws IOException 
	 */
	@RequestMapping(value = "/platUploadfile/addImage", method = RequestMethod.POST)
	@ResponseBody
	public String addImage(@RequestParam("upfile") CommonsMultipartFile upfile			
			,@RequestParam(value="fileTag" , required=false) Integer fileTag			
			,HttpServletRequest request) throws IOException
	{
		UploadBean bean=null;
		if(fileTag==null){
			bean= uploadFile.updateFile(upfile,request,storeFilePath,UploadFile.UPLOAD_FILE);
		}
		else if(fileTag==PlatUploadfile.CONTENT_IMAGE_TAG){
			bean= uploadFile.updateFile(upfile,request,storeFilePath,UploadFile.UPLOAD_IMAGE);
		}
		else if(fileTag==PlatUploadfile.IMAGE_TAG){
			bean= uploadFile.updateFile(upfile,request,storeImagePath,UploadFile.UPLOAD_IMAGE);
		}
		else if(fileTag==PlatUploadfile.LOGO_TAG){
			bean= uploadFile.updateFile(upfile,request,storeLogoPath,UploadFile.UPLOAD_IMAGE);
		}
		String result=bean.toString();
		return result;
	}

	/***
	 * 文件删除
	 * @throws IOException 
	 */
	@RequestMapping(value = "/platUploadfile/delete")
	@ResponseBody
	public ObjectMessages delete(Map<String, Object> model
			,@RequestParam(value="fileId" , required=false) String fileId)
	{
	    String bi[] = fileId.split(",");		
		for(int i=0; i<bi.length; i++){
			this.platUploadfileService.delete(Integer.parseInt(bi[i]));
	    }
		return messageUtil.messages("common.delete.success");
	}
	
	/**
	 * 判断文件格式是否正确
	 */
	private static boolean checkFileExt(String ext, String exts)
	{
		RegexpMatcher matcher = RegexpUtils.getMatcher("\\.?(" + exts + ")");
		return matcher.matches(ext.toLowerCase());
	}
}